<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2017/11/11
 * Time: 07:52 AM
 */
class PHZ_Tools
{

    /**
     * 获取下一张底牌
     * @param $db_connect
     * @param $room_id
     * @return mixed
     */
    public static function __get_next_number( $db_connect , $room_id ){
        $room_info        = $db_connect->select('*')->from('tt_room')->where("room_id= '". $room_id ."' ")->row();
        $card_info        = $db_connect->select('*')->from('tt_room_card')->where('jid = '. $room_info['room_js'] .' and rid=' . $room_info['room_id'] )->row();//取出随便那个人的底牌信息
        $dipai            = $card_info['dp'];
        $dipai            = explode(",",$dipai);
        $next_card_number = $dipai[0];unset($dipai[0]);
        $db_connect->update('tt_room_card')->cols(array('dp'=> implode(",",$dipai)  ))->where('jid = '. $room_info['room_js'] .' and rid=' . $room_info['room_id'] )->query();
        return $next_card_number;
    }


    /**
     * 1.情况1：摸牌后的畏，跑，提-立即检查;;若检查通过存在这3种情况，则向所有用户下发这三种情况的通知；
     * 2.情况2：若不能存在这3种情况；则向所有用户下发明牌通知；且同时判断所有玩家是否能吃、胡、跑、碰、下跑 （这里的碰、跑、下跑，自己就不需要检测了；因为可以的话，就已经畏跟提了）
     * @param $room_id           房间号
     * @param $user_id           权利交接人
     * @param $mop_uid           摸牌人
     * @param $card_number       新摸牌，也就是下一张底牌的牌号
     */
    public static function __mopai_wei_ti_pao_chk( $room_id , $user_id , $mop_uid , $card_number , $db_connect = null){
        //取出房间信息
        $room_info          = $db_connect->select('*')->from('tt_room')->where("room_id= '". $room_id ."' ")->row();
        //取出该房间当前这一局的摸牌人的手牌信息
        $my_card_info       = $db_connect->select('*')->from('tt_room_card')->where("uid = '". $mop_uid ."' and jid = '". $room_info['room_js'] ."' and rid= '". $room_id ."' ")->row();
        //判断是否能提（跟手里的3张牌组4张）
        $mopai_is_pao       = PHZ_Mopai::__mopai_ziji_qipao( $room_info , $my_card_info , $mop_uid , $card_number , $db_connect );
        //判断是否能畏（跟本方手里的牌组3张）
        $mopai_is_wei       = PHZ_Mopai::__mopai_chk_wei( $room_info , $my_card_info ,$mop_uid , $card_number ,  $db_connect );
        //如果不能提也不能畏的情况下；判断是否已经畏过这个字；然后变成了“惊” ； 2018.02. - BUG
        if( $mopai_is_wei != true && $mopai_is_pao['status'] != true ){
            $mopai_is_pao = array();$mopai_is_pao['status'] = false;$mopai_is_pao['is_chongpao'] = 0;//初始化数组
            $card_is_wei = false;$card_wei    = explode(",", $my_card_info['card_wei'] );
            foreach ( $card_wei as $key => $value ){if( $value == $card_number ){$card_is_wei = true;}}//该摸牌人是否畏过该牌
            if( $card_is_wei == true ){
                //设置本次为跑牌
                $mopai_is_pao['status'] = true;
                //设置本次是否为重跑
                if( $my_card_info['ti_pao'] >= 1 ){
                    $mopai_is_pao['is_chongpao'] = 1;
                }
                //进行增息操作;然后向前端输出畏牌后的自摸的惊操作
                PHZ_SuanXi::__xi( $room_info , $mop_uid , "wei_and_jing" , $card_number , $db_connect );
                //增加下牌;3变4
                $update_xp = str_replace( $card_number . "_" . $card_number . "_" . $card_number , $card_number . "_" . $card_number . "_" . $card_number . "_" . $card_number , $my_card_info['xp'] );
                $card_ti   = $my_card_info['card_ti'] . $card_number . ",";//2018.03.06-畏牌变京牌后增加一个ti牌记录
                $db_connect->update('tt_room_card')->cols(array( 'xp' => $update_xp , 'ti_pao' => ($my_card_info['ti_pao']+1) , 'card_ti' => $card_ti  ))->where('id=' . $my_card_info['id'] )->query();
                //设置出牌权
                PHZ_Room::__setThisPutUser( $room_info['room_id'] , $mop_uid , $db_connect );
                //发送日志
                $temp = array();
                $temp['pl']          = 34;
                $temp['card_number'] = $card_number;
                $temp['put_uid']     = $mopai_is_pao['is_chongpao'] == 1 ? 0 : $mop_uid;//重跑的情况下没有出牌权,没有重跑则是摸牌人出牌
                $temp['mop_uid']     = 0;//全部人丧失摸牌权
                PHZ_Log::__send_user_log( $room_info , $mop_uid , $temp  , $db_connect );
            }
        }
        //1.如果自己能畏或者能提，则自己自己的判胡操作;
        //2.如果自己能胡，则等待自己进行胡或者“过”的操作；否则不能胡的情况下；
        //3.如果自己不能胡，如果重跑，则下家自动摸牌；如果非重跑，则等待自己出牌
        if( $mopai_is_wei == true || $mopai_is_pao['status'] == true ){
            $default_huxi = PHZ_Tools::__get_user_xpAndKanzi_Huxi( $room_id ,$mop_uid  );//获取我的基本息数
            //由于是自摸的畏提胡，需要进行基础牌更换操作(如果胡的字是畏或者跑的字，是不能胡的)
            $my_card_info        = $db_connect->select('*')->from('tt_room_card')->where("uid = '". $mop_uid ."' and jid = '". $room_info['room_js'] ."' and rid= '". $room_id ."' ")->row();//BUG修复；这里要重新获取一次手牌信息
            if( trim( $my_card_info['sp'] ) != "" && $my_card_info['sp'] != "," ) {
                $my_card_info['sp'] = explode(",", $my_card_info['sp']);
                $temp_cardnumber    = $my_card_info['sp'][0];
                unset($my_card_info['sp'][0]);
                $my_card_info['sp'] = implode(",", $my_card_info['sp']);
                $canHu = PHZ_CanHu::__isCan_Hu_Pai($default_huxi, $my_card_info['sp'], $temp_cardnumber, -1, $room_info);//进行胡牌判定操作
            }else{
                $canHu = array();$canHu['canHu'] = false;
            }
            if( $canHu['canHu'] == true ){//能胡，给自身发送胡的信息,由自己去做操作,是胡还是不胡
                //获取我的基本位置
                $my_index = PHZ_User::__get_user_Room_Index( $room_info , $mop_uid );
                //更新自己is_hu状态
                $db_connect->update('tt_room')->cols(array('p' . ($my_index) . '_is_hu' => 1))->where('room_id=' . $room_id)->query();//更新当前房间当前位置用户的胡状态
                //重设tm:bug
                PHZ_Room::__setThisMopCard( $room_info['room_id'] , $mop_uid , $card_number , false , $db_connect );
                //发送胡牌信息
                $temp = array();
                $temp['pl']          = 22;//自摸胡牌可按钮通知
                $temp['card_number'] = $card_number;//牌号 - 当前为所有人都能看到牌号
                $temp['put_uid']     = 0;//所有人丧失出牌权
                $temp['mop_uid']     = 0;//全部人丧失摸牌权
                $temp['hu_is_wp']    = 1;//是否为畏跑胡？  - 畏跑胡的判胡情况下有点不同
                PHZ_Log::__send_user_log_IN_Single( $room_info , $mop_uid , $mop_uid , $temp  , $db_connect );
                //设置出牌权
                PHZ_Room::__setThisPutUser( $room_info['room_id'] , $temp['put_uid'] , $db_connect );
            }else{
                //2018.01.08新BUG：最后畏完牌没有牌了，需要进行一次无牌判胡操作；----;如果没牌了，而且胡息数是够了的情况下；直接胡牌；如果不够；下家自动摸牌 - 畏牌的时候要判断了如果不够的情况下，是不允许畏牌的；；
                if( $mopai_is_wei == true && trim( $my_card_info['sp'] ) == "" ) {
                    if( $default_huxi >= MININUM_HUXI ){
                        PHZ_Scoring::__game_Single_END( $room_info , $default_huxi , $mop_uid , 0 , $card_number , 1 , $db_connect );//直接计分结束
                        return true;
                    }else{
                        PM_n::__index($room_info, $mop_uid, 0, $db_connect);//按理说这里是执行不到的
                    }
                }else {
                    if ($mopai_is_pao['status'] == true && $mopai_is_pao['is_chongpao'] == 1) {
                        PM_n::__index($room_info, $mop_uid, 0, $db_connect);
                    }
                }
            }
            //设置当前房间摸牌人以及牌号 - 有畏或者有跑；清空
            if( $canHu['canHu'] == false ) {
                PHZ_Room::__setThisMopCard($room_info['room_id'], 0, 0, true, $db_connect);
            }
            //返回true
            return true;
        }
        //4.如果自己不能畏或者不能提，则进行全局用户的摸牌广播；
        $temp = array();
        $temp['pl']          = 13;//13为摸牌人摸牌后，自身不能进行畏或者碰以后；牌面公示
        $temp['card_number'] = $card_number;//牌号 - 当前为所有人都能看到牌号
        $temp['put_uid']     = 0;//所有人丧失出牌权
        $temp['mop_uid']     = 0;//全部人丧失摸牌权
        /////////////////////////////////////////////////////////////////////////////////////////是否存在操作？--2017.12.11
        $card_info = $db_connect->select('*')->from('tt_room_card')->where("jid = '". $room_info['room_js'] ."' and rid= '". $room_id ."' ")->query();
        $temp['is_mp_op']    = PM_c_aux::__queryHandPut_ISoperation_isMOP( $room_info , $card_info ,$mop_uid , $card_number , $my_card_info , $db_connect );
        /////////////////////////////////////////////////////////////////////////////////////////是否存在操作？--2017.12.11
        PHZ_Log::__send_user_log( $room_info , $mop_uid , $temp  , $db_connect );
        //设置出牌权
        PHZ_Room::__setThisPutUser( $room_info['room_id'] , $temp['put_uid'] , $db_connect );
        //5.牌面公示后的每个用户的胡、提、跑、碰、吃检查
        PHZ_Open::__mopai_all_user_chk( $room_id , $card_number , $mop_uid , $db_connect );
    }

    /**
     * 用户进行吃牌后，手牌更新操作
     * 1.更新方式：将用户当前的手牌基础上加上这个新吃进来的牌；再依次删除所有吃牌的牌（这样可以把比牌情况也同时清除）
     * @param $eat_card_info   吃牌人手中当前的牌面信息
     * @param $card_number     吃牌的号
     * @param $eat_card        吃牌的组合方式
     * @param $db_connect      数据库链接
     */
    public static function __chi_pai_update_sp( $eat_card_info  , $card_number , $eat_card  ){
        //将手牌与新吃的牌组合到一起
        $user_sp_info = $eat_card_info['sp'] . "," .  $card_number;
        $user_sp_info = explode(",", $user_sp_info );
        //将新组合出来的手牌进行遍历删除
        $eat_array = array();
        $eat_card  = explode(",",$eat_card);
        foreach ( $eat_card as $key => $value ){
            $eat_card_info = explode("_", $value );
            foreach ( $eat_card_info as $key_1 => $value_1 ){
                array_push( $eat_array , $value_1 );
            }
        }
        //删除所有需要被删除的手中的牌
        foreach ( $eat_array as $key => $value ){
            foreach ( $user_sp_info as $key_1 => $value_1 ){
                if( $value_1 == $value ){
                    unset( $user_sp_info[ $key_1 ] );
                    break;//每次清除1个就退出；因为不能多删；只能删一个
                }
            }
        }
        //返回重新组合后的手牌信息
        return implode(",", $user_sp_info );
    }

    /**
     * 设置所有玩家的胡碰吃当前属性为0
     * @param $room_id
     * @param $db_connect
     * @return mixed
     */
    public static function __set_room_alluser_hu_chi_peng_0( $room_id , $db_connect ){
        $data = array();
        $data['p1_is_chi'] = 0;$data['p2_is_chi'] = 0;$data['p3_is_chi'] = 0;$data['p4_is_chi'] = 0;
        $data['p1_is_peng'] = 0;$data['p2_is_peng'] = 0;$data['p3_is_peng'] = 0;$data['p4_is_peng'] = 0;
        $data['p1_is_hu'] = 0;$data['p2_is_hu'] = 0;$data['p3_is_hu'] = 0;$data['p4_is_hu'] = 0;
        return $db_connect->update('tt_room')->cols( $data )->where('room_id=' . $room_id )->query();
    }

    /**
     * 通过房间信息跟用户ID获得该用户在该房间的第几个位置上
     * @param $room_info
     * @param $user_id
     * @return int
     */
    public static function __get_user_in_room_index( $room_info , $user_id ){
        if( $room_info['room_player_1'] == $user_id ){return 1;}
        if( $room_info['room_player_2'] == $user_id ){return 2;}
        if( $room_info['room_player_3'] == $user_id ){return 3;}
        if( $room_info['room_player_4'] == $user_id ){return 4;}
        echo "error_notIndex_" . $user_id;
    }

    /**
     * 获取一个用户的胡息数
     * @param $room_id   房间号
     * @param $user_id   用户ID
     * @param $from      查询来自
     * @param $who_find  谁在查
     * @return int       息数（整形）
     */
    public static function __get_user_xpAndKanzi_Huxi( $room_id , $user_id , $from = "all_get" , $who_find = 0 ){
        $room_info  = Events::$db->select('*')->from('tt_room')->where("room_id= '". $room_id ."' ")->row();
        $card_info  = Events::$db->select('*')->from('tt_room_card')->where('uid = '. $user_id .' and jid = '. $room_info['room_js'] .' and rid=' . $room_info['room_id'] )->row();
        $huxi       = (int)$card_info['huxi'];
        if( $from == 'index_get' && $who_find != $card_info['uid'] ){
            $card_wei = explode("," , $card_info['card_wei'] );
            $card_ti  = explode("," , $card_info['card_ti'] );
            //检查是否有提牌；提牌大字-12，小字-9
            foreach ( $card_ti as  $key => $value ){
                if( $value >= 1 && $value <= 20 ){
                    if( $value <= 10 ){ $huxi = $huxi - 9; }
                    if( $value >= 11 ){ $huxi = $huxi - 12; }
                }
            }
            //检查是否有畏牌，畏牌大字-6，小字-3 ; ;注意这里因为畏后的京也会有畏的记录；所以这里需要判断如果有提的记录了这个牌，就不需要再判断畏的减息了
            foreach ( $card_wei as  $key => $value ){
                if( $value >= 1 && $value <= 20 && !in_array( $value , $card_ti ) ){
                    if( $value <= 10 ){ $huxi = $huxi - 3; }
                    if( $value >= 11 ){ $huxi = $huxi - 6; }
                }
            }
        }
        return $huxi;
    }

}